﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Diagnostics;
using System.Xml;
using System.ComponentModel;
using System.Globalization;
using System.Xml.XPath;
using System.Collections.Specialized;

namespace AppModifier
{
    public class Tuple
    {
        public int Key;
        public StringBuilder Value;
    }

    class Program
    {
        private static Dictionary<string, int> _files = new Dictionary<string, int>();
        private static string _logFileName = string.Format(@"AppModifier_{0}.txt", DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss.fffffff"));
        private static string _fileName = string.Empty;
        private static Dictionary<string, Tuple> _messages = new Dictionary<string, Tuple>();
        private static Dictionary<string, string> _assemblyVersions = new Dictionary<string, string>();
        private static Dictionary<string, string> _deparaServidores = new Dictionary<string, string>();

        static void Main(string[] args)
        {
            try
            {
                LoadVersions();
                DeparaServidores();

                string patterns = ConfigurationManager.AppSettings["Patterns"].Trim();
                string dropPath = ConfigurationManager.AppSettings["DropPath"].Trim();

                string[] dropPathSplit = dropPath.Split(';');

                if (dropPathSplit.Length > 1)
                {
                    foreach (string path in dropPathSplit)
                    {
                        if (!string.IsNullOrEmpty(path.Trim()))
                        {
                            try
                            {
                                LoadDirectory(patterns, path.Trim());
                            }
                            catch (Exception ex)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Cannot read files from: {0}", path);
                                Console.WriteLine(ex.Message);
                                Console.WriteLine("");
                            }
                        }
                    }
                }
                else
                {
                    LoadDirectory(patterns, dropPath);
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
            }

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" ");
            Console.WriteLine("Press any key to continue . . .");
            Console.ResetColor();
            Console.ReadLine();
        }

        private static void LoadDirectory(string patterns, string dropPath)
        {
            string[] patternSplit = patterns.Split(';');

            if (patternSplit.Length > 1)
            {
                foreach (string pattern in patternSplit)
                {
                    LoadFiles(pattern, dropPath);
                }
            }
            else
            {
                LoadFiles(patterns, dropPath);
            }
        }

        private static void LoadFiles(string pattern, string dropPath)
        {
            Console.Title = Path.Combine(dropPath, pattern);

            Console.ForegroundColor = ConsoleColor.Green;

            if (!Directory.Exists(dropPath))
                throw new DirectoryNotFoundException(dropPath);

            foreach (string file in Directory.GetFiles(dropPath, pattern, SearchOption.AllDirectories))
            {
                Modify(Path.GetFullPath(file));
            }
        }

        private static void Modify(string file)
        {
            try
            {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Reading {0}", file);

                _fileName = file;

                WriteText("=================================================");
                WriteText(file);
                WriteText("=================================================");

                if (file.EndsWith(".cs") || file.EndsWith(".sln"))
                {
                    ModifyTextFile(file);
                }
                else if (file.EndsWith(".config") || file.EndsWith(".svcmap") || file.EndsWith(".csproj") || file.EndsWith(".vbproj"))
                {
                    ModifyXmlFile(file);
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Cannot read file: {0}", file);
                Console.WriteLine(ex.Message);
                Console.WriteLine("");

                File.AppendAllText(_logFileName, Environment.NewLine);
                File.AppendAllText(_logFileName, "Error:");
                File.AppendAllText(_logFileName, ex.Message);
                File.AppendAllText(_logFileName, Environment.NewLine);
            }
        }

        private static void ModifyTextFile(string file)
        {
            //ModifyVS2010Solution(file);

            //ModifyDbType(file);

            //ModifyProtectionLevel(file);

            //ModifyTextFileFaultContracts(file);

            //ModifyTextSecutiry(file);

            //ModifyCheckUserAcessBMF(file);

            //ModifyCheckUserAcessBovespa(file);

            //ModifyAssemblyVersion(file);

            //CreateSvcFiles(file);
        }

        private static void ModifyXmlFile(string file)
        {
            XDocument document = XDocument.Load(file);

            bool fileUpdated = false;

            #region Unificacao Portas

            //ModifyNetTcpBinding(document, ref fileUpdated);

            //ModifyTcpTransport(document, ref fileUpdated);

            //ModifyPortServer(document, ref fileUpdated);

            //ModifyPortClient(document, ref fileUpdated);

            //ModifyServiceReferences(document, ref fileUpdated);

            //ModifySetMexTcpBinding(document, ref fileUpdated);

            //NotifyMexBinding(document, ref fileUpdated);

            //ModifyCustomBinding(document, ref fileUpdated); 

            #endregion

            #region EnterpriseLibrary

            //ModifyVersionEnterpriseLibraryCaching(document, ref fileUpdated);

            //ModifyVersionEnterpriseLibraryCachingConfiguration(document, ref fileUpdated);

            //ModifyVersionEnterpriseDataConfiguration(document, ref fileUpdated);

            //ModifyVersionEnterpriseLibraryLogging(document, ref fileUpdated);

            //ModifyVersionEnterpriseLibraryLoggingConfiguration(document, ref fileUpdated);

            //ModifyReferenceEnterpriseLibrary(document, ref fileUpdated);

            #endregion

            #region Reference Framework

            //ModifyReferencePrivate(file, document, ref fileUpdated, true);

            //ModifyProjectReferencePrivate(file, document, ref fileUpdated, true);

            //ModifyReferenceSpecificVersion(file, document, ref fileUpdated);

            //IncludePSEReference(document, ref fileUpdated);

            RemoveScc(document, ref fileUpdated);

            //RemoveAppSettingsMTA(document, ref fileUpdated);

            //RemoveReferenceCalculationCore(document, ref fileUpdated);

            //ListIncludes(document, ref fileUpdated);

            //ChangePlatformTarget(document, ref fileUpdated);

            //ChangePlatformTargetReference(document, ref fileUpdated);

            //RemoveObsoletsTags(document, ref fileUpdated);

            //ChangeOutputPath(document, ref fileUpdated);

            //ModifyValues(file, document, ref fileUpdated);

            //ModifyHintPathPSEComponents(document, ref fileUpdated);

            //ModifyVS2010Project(document, ref fileUpdated);

            #endregion

            #region Alteracoes em configs do client

            //RemoveClientBehaviors(document, ref fileUpdated);

            //RemoveClientBindings(document, ref fileUpdated);

            //ModifyClientEndpoint(document, ref fileUpdated);

            #endregion

            #region Alteracoes em configs do server

            //IncludeSystemDiagnosticsTag(document, ref fileUpdated);

            //ModifyServiceBehavior(document, ref fileUpdated);

            //ModifyServiceBinding(document, ref fileUpdated);

            //ModifyService(document, ref fileUpdated);

            #endregion

            //if (fileUpdated)
            {
                PendEdit(file);

                document.Save(file);

                if (_messages[_fileName].Key > 3)
                {
                    File.AppendAllText(_logFileName, _messages[_fileName].Value.ToString());
                }
            }
        }

        #region Text File

        private static void ModifyVS2010Solution(string file)
        {
            string originalContent = File.ReadAllText(file, Encoding.Default);

            string content = originalContent.Replace("Visual Studio 2008", "Visual Studio 2010");

            content = content.Replace("Format Version 10.00", "Format Version 11.00");

            if (originalContent != content)
            {
                PendEdit(file);

                SaveFile(file, content);
            }
        }

        private static void ModifyDbType(string file)
        {
            string originalContent = File.ReadAllText(file, Encoding.Default);

            string content = originalContent.Replace("DbType.Boolean", "DbType.Int32");

            if (originalContent != content)
            {
                PendEdit(file);

                SaveFile(file, content);
            }
        }

        private static void ModifyTextSecutiry(string file)
        {
            string originalContent = File.ReadAllText(file, Encoding.Default);

            string content = originalContent.Replace("Secutiry", "Security");

            if (originalContent != content)
            {
                PendEdit(file);

                SaveFile(file, content);
            }
        }

        private static void ModifyTextFileFaultContracts(string file)
        {
            string originalContent = File.ReadAllText(file, Encoding.Default);

            string content = Regex.Replace(originalContent, @"\""\s*\+\s*\""", string.Empty);

            //content = content.Replace(@"http://schemas.datacontract.org/2004/07/ibba.raroc.Wcf.Entidades", @"http://www.sinacor.com.br/Sinacor.Infra.Common.Exceptions.FaultContracts");

            if (originalContent != content)
            {
                PendEdit(file);

                SaveFile(file, content);
            }
        }

        private static void ModifyProtectionLevel(string file)
        {
            string originalContent = File.ReadAllText(file, Encoding.Default);

            string content = originalContent.Replace("ProtectionLevel=System.Net.Security.ProtectionLevel.EncryptAndSign,", "");
            content = content.Replace("ProtectionLevel=System.Net.Security.ProtectionLevel.EncryptAndSign,", "");

            if (originalContent != content)
            {
                PendEdit(file);

                SaveFile(file, content);
            }
        }

        private static void ModifyCheckUserAcessBMF(string file)
        {
            string originalContent = GetContentEncoding(file);

            string content = originalContent;

            //[C:\DSEPROJ\SinaOMF\NET\MAIN\VC\VC\Source\Servicos\Bmf\AcertoCorretagem\BusinessLogic\AcertoSerie.cs] -BMF
            //Line 541 :             if (!AuthorizationContext.Current.CheckUserAccess("CACS"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"CACS\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"CACS\", \"BMF\"))");

            //[C:\DSEPROJ\SinaOMF\NET\MAIN\VC\VC\Source\Servicos\Bmf\AcertoTaxas\BusinessLogic\AcertoScalper.cs] -BMF
            //Line 319 :             if (!AuthorizationContext.Current.CheckUserAccess("CSCP"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"CSCP\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"CSCP\", \"BMF\"))");

            //[C:\DSEPROJ\SinaOMF\NET\MAIN\VC\VC\Source\Servicos\Bmf\Ordens\BusinessLogic\BatimentoMesaAuxiliar.cs] - OMF
            //Line 22 :             return AuthorizationContext.Current.CheckUserAccess("TRCP");
            content = content.Replace("return AuthorizationContext.Current.CheckUserAccess(\"TRCP\");", "return AuthorizationContext.Current.CheckUserAccess(\"TRCP\", \"OMF\");");

            //[C:\DSEPROJ\SinaOMF\NET\MAIN\VC\VC\Source\Servicos\Bmf\Ordens\BusinessLogic\Boleto.cs] - OMF
            //Line 69 :             if (!Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MBATOP"))
            content = content.Replace("if (!Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MBATOP\"))", "if (!Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MBATOP\", \"OMF\"))");
            //Line 311 :             bool matPre = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MATPRE");
            content = content.Replace("bool matPre = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MATPRE\");", "bool matPre = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MATPRE\", \"OMF\");");
            //Line 312 :             bool mCoMes = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MCOMES");
            content = content.Replace("bool mCoMes = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MCOMES\");", "bool mCoMes = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MCOMES\", \"OMF\");");
            //Line 362 :             bool matPre = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MATPRE");
            content = content.Replace("bool matPre = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MATPRE\");", "bool matPre = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MATPRE\", \"OMF\");");
            //Line 363 :             bool mCoMes = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MCOMES");
            content = content.Replace("bool mCoMes = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MCOMES\");", "bool mCoMes = Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MCOMES\", \"OMF\");");

            //[C:\DSEPROJ\SinaOMF\NET\MAIN\VC\VC\Source\Servicos\Bmf\Ordens\BusinessLogic\ManipulacaoCompleta.cs] - OMF
            //Line 36 :             if (!AuthorizationContext.Current.CheckUserAccess("AORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"AORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"OMF\"))");
            //Line 43 :                 if (!AuthorizationContext.Current.CheckUserAccess("D1SIM"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\", \"OMF\"))");
            //Line 287 :             if (!AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"OMF\"))");
            //Line 310 :                 if (!AuthorizationContext.Current.CheckUserAccess("D1SIM"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\", \"OMF\"))");

            //[C:\DSEPROJ\SinaOMF\NET\MAIN\VC\VC\Source\Servicos\Bmf\Ordens\BusinessLogic\ManipulacaoRapida.cs] - OMF
            //Line 90 :             bool matpreAccess = AuthorizationContext.Current.CheckUserAccess("MATPRE");
            content = content.Replace("bool matpreAccess = AuthorizationContext.Current.CheckUserAccess(\"MATPRE\");", "bool matpreAccess = AuthorizationContext.Current.CheckUserAccess(\"MATPRE\", \"OMF\");");
            //Line 91 :             bool mcomesAccess = AuthorizationContext.Current.CheckUserAccess("MCOMES");
            content = content.Replace("bool mcomesAccess = AuthorizationContext.Current.CheckUserAccess(\"MCOMES\");", "bool mcomesAccess = AuthorizationContext.Current.CheckUserAccess(\"MCOMES\", \"OMF\");");

            //[C:\DSEPROJ\SinaOMF\NET\MAIN\VC\VC\Source\Servicos\Bmf\Ordens\ResourceAccess\Ordem.cs] - OMF
            //Line 239 :                     if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))
            content = content.Replace("if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))", "if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))");
            //Line 255 :                         else if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.CodigoOperador != 0))
            content = content.Replace("else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.CodigoOperador != 0))", "else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.CodigoOperador != 0))");
            //Line 617 :                     if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))
            content = content.Replace("if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))", "if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))");
            //Line 632 :                         else if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.CodigoOperador != 0))
            content = content.Replace("else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.CodigoOperador != 0))", "else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.CodigoOperador != 0))");
            //Line 984 :                     if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))
            content = content.Replace("if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))", "if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))");
            //Line 993 :                     else if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.CodigoOperador != 0))
            content = content.Replace("else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.CodigoOperador != 0))", "else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.CodigoOperador != 0))");
            //Line 1000 :                         else if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.CodigoOperador != 0))
            content = content.Replace("else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.CodigoOperador != 0))", "else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"BMF\")) && (request.CodigoOperador != 0))");
            //Line 1321 :                     if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))
            content = content.Replace("if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))", "if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.TipoOrigem != TipoOrigem.Menu /* e quando vem de alguma tela */))");
            //Line 1330 :                     else if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.CodigoOperador != 0))
            content = content.Replace("else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.CodigoOperador != 0))", "else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.CodigoOperador != 0))");
            //Line 1337 :                         else if ((AuthorizationContext.Current.CheckUserAccess("CNOSUB")) && (request.CodigoOperador != 0))
            content = content.Replace("else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\")) && (request.CodigoOperador != 0))", "else if ((AuthorizationContext.Current.CheckUserAccess(\"CNOSUB\", \"OMF\")) && (request.CodigoOperador != 0))");

            if (originalContent != content)
            {
                PendEdit(file);

                SaveFile(file, content);
            }
        }

        private static void ModifyCheckUserAcessBovespa(string file)
        {
            string originalContent = GetContentEncoding(file);

            string content = originalContent;

            //[C:\DSEPROJ\SinaORD\NET\PROD\P1I9\SPK\Source\Process\Bovespa\ControleMovimentoBolsa\Server\ProcessLogic\AberturaMovimentoBolsa.cs] - BOL
            //Line 240 :             if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess("BABERT"))
            content = content.Replace("if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BABERT\"))", "if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BABERT\", \"BOL\"))");

            //[C:\DSEPROJ\SinaORD\NET\PROD\P1I9\SPK\Source\Process\Bovespa\ControleMovimentoBolsa\Server\ProcessLogic\ConsolidacaoMovimentoBolsa.cs]  - BOL
            //Line 217 :             if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess("BCONSO"))
            content = content.Replace("if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BCONSO\"))", "if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BCONSO\", \"BOL\"))");

            //[C:\DSEPROJ\SinaORD\NET\PROD\P1I9\SPK\Source\Process\Bovespa\ControleMovimentoBolsa\Server\ProcessLogic\ControleMovimentoBolsa.cs]  - BOL
            //Line 173 :             if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess("BPROCE"))
            content = content.Replace("if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BPROCE\"))", "if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BPROCE\", \"BOL\"))");

            //[C:\DSEPROJ\SinaORD\NET\PROD\P1I9\SPK\Source\Process\Bovespa\ControleMovimentoBolsa\Server\ProcessLogic\FechamentoMovimentoBolsa.cs]  - BOL
            //Line 443 :             if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess("BFECHA"))
            content = content.Replace("if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BFECHA\"))", "if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BFECHA\", \"BOL\"))");

            //[C:\DSEPROJ\SinaORD\NET\PROD\P1I9\SPK\Source\Process\Bovespa\ControleMovimentoBolsa\Server\ProcessLogic\ReaberturaMovimentoBolsa.cs]  - BOL
            //Line 356 :             if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess("BREABR"))
            content = content.Replace("if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BREABR\"))", "if (!AuthorizationContext<SinacorAuthorizationContext>.Current.CheckUserAccess(\"BREABR\", \"BOL\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\AlocacaoCarteiraVendaDescoberta.cs] - ORD
            //Line 563 :                     if(!(AuthorizationContext.Current.CheckUserAccess("MONC")))
            content = content.Replace("if(!(AuthorizationContext.Current.CheckUserAccess(\"MONC\")))", "if(!(AuthorizationContext.Current.CheckUserAccess(\"MONC\", \"ORD\")))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\AlocacaoCoberturaTermo.cs] - ORD
            //Line 60 :                     bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("GJUS");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"GJUS\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"GJUS\", \"ORD\");");
            //Line 60 :                     bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("GJUS");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"GJUS\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"GJUS\", \"ORD\");");
            //Line 154 :                     if (AuthorizationContext.Current.CheckUserAccess("GJUS"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"GJUS\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"GJUS\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\DistribuicaoNegocio.cs] - ORD
            //Line 179 :                 if (AuthorizationContext.Current.CheckUserAccess("DISNEG"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"DISNEG\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"DISNEG\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\DivergenciaAlocacao.cs] - ORD
            //Line 60 :             bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("NEGO");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\");");
            //Line 60 :             bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("NEGO");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\");");
            //Line 108 :             bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("NEGO");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\");");
            //Line 108 :             bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("NEGO");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\");");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\MensagemErroRecebida.cs] - ORD
            //Line 81 :                     if (AuthorizationContext.Current.CheckUserAccess("ORDNIM"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"ORDNIM\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"ORDNIM\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\MonitorAlocacao.cs] - ORD
            //Line 365 :             if (AuthorizationContext.Current.CheckUserAccess("ORDM"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"ORDM\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"ORDM\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\NegocioAlocado.cs] - ORD
            //Line 69 :             if (AuthorizationContext.Current.CheckUserAccess("NEGO"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\NegocioPendenteAlocacao.cs] - ORD
            //Line 69 :             if (AuthorizationContext.Current.CheckUserAccess("NEGO"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\Recompra.cs] - ORD
            //Line 316 :             bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("NEGO") & AuthorizationContext.Current.CheckUserAccess("MNEG");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\") & AuthorizationContext.Current.CheckUserAccess(\"MNEG\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\") & AuthorizationContext.Current.CheckUserAccess(\"MNEG\", \"ORD\");");
            //Line 316 :             bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("NEGO") & AuthorizationContext.Current.CheckUserAccess("MNEG");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\") & AuthorizationContext.Current.CheckUserAccess(\"MNEG\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\") & AuthorizationContext.Current.CheckUserAccess(\"MNEG\", \"ORD\");");
            //Line 316 :             bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess("NEGO") & AuthorizationContext.Current.CheckUserAccess("MNEG");
            content = content.Replace("bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\") & AuthorizationContext.Current.CheckUserAccess(\"MNEG\");", "bool retornoCheckUserAccess = AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\") & AuthorizationContext.Current.CheckUserAccess(\"MNEG\", \"ORD\");");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\Alocacao\BusinessLogic\Solicitacao.cs] - ORD
            //Line 147 :             if (AuthorizationContext.Current.CheckUserAccess("NEGO"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\"))");
            //Line 186 :             if (AuthorizationContext.Current.CheckUserAccess("NEGO"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"NEGO\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\ManutencaoOrdens\BusinessLogic\BusinessRulesValidation\ValidadorAlteracaoOrdem.cs] - ORD
            //Line 190 :                         if (AuthorizationContext.Current.CheckUserAccess("APAP"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"APAP\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"APAP\", \"ORD\"))");
            //Line 332 :                     if (AuthorizationContext.Current.CheckUserAccess("ACLI"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"ACLI\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"ACLI\", \"ORD\"))");
            //Line 572 :                 if (AuthorizationContext.Current.CheckUserAccess("ARED"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"ARED\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"ARED\", \"ORD\"))");
            //Line 653 :                 if (AuthorizationContext.Current.CheckUserAccess("AQTD"))
            content = content.Replace("if (AuthorizationContext.Current.CheckUserAccess(\"AQTD\"))", "if (AuthorizationContext.Current.CheckUserAccess(\"AQTD\", \"ORD\"))");
            //Line 843 :                         if (!AuthorizationContext.Current.CheckUserAccess("D1SIM"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\ManutencaoOrdens\BusinessLogic\BusinessRulesValidation\ValidadorCancelamentoDetalheOrdem.cs] - ORD
            //Line 38 :             bool possuiPermissao = AuthorizationContext.Current.CheckUserAccess("D1SIM");
            content = content.Replace("bool possuiPermissao = AuthorizationContext.Current.CheckUserAccess(\"D1SIM\");", "bool possuiPermissao = AuthorizationContext.Current.CheckUserAccess(\"D1SIM\", \"ORD\");");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\ManutencaoOrdens\BusinessLogic\BusinessRulesValidation\ValidadorCancelamentoOrdem.cs] - ORD
            //Line 111 :             if (!AuthorizationContext.Current.CheckUserAccess("D1SIM"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"D1SIM\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\ManutencaoOrdens\BusinessLogic\Casamento.cs] - ORD
            //Line 244 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD") && !AuthorizationContext.Current.CheckUserAccess("AORD") && !AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");
            //Line 244 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD") && !AuthorizationContext.Current.CheckUserAccess("AORD") && !AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");
            //Line 244 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD") && !AuthorizationContext.Current.CheckUserAccess("AORD") && !AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\ManutencaoOrdens\BusinessLogic\Justificativa.cs] - ORD
            //Line 66 :             if (Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MORD"))
            content = content.Replace("if (Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MORD\"))", "if (Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MORD\", \"ORD\"))");
            //Line 116 :             if (Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MORD"))
            content = content.Replace("if (Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MORD\"))", "if (Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MORD\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\ManutencaoOrdens\BusinessLogic\ManutencaoOrdens.cs] - ORD
            //Line 80 :             if (!Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess("MORD"))
            content = content.Replace("if (!Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MORD\"))", "if (!Sinacor.Infra.Service.Security.Authorization.AuthorizationContext.Current.CheckUserAccess(\"MORD\", \"ORD\"))");
            //Line 293 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\"))");
            //Line 353 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\"))");
            //Line 449 :             if (!AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");
            //Line 549 :             if (!AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");
            //Line 691 :             if (!AuthorizationContext.Current.CheckUserAccess("AORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"AORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"ORD\"))");

            //[C:\DSEPROJ\SinaORD\NET\MAIN\VC\VC\Source\Servicos\Bovespa\ManutencaoOrdens\BusinessLogic\PreBoleto.cs] - ORD
            //Line 489 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD") && !AuthorizationContext.Current.CheckUserAccess("AORD") && !AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");
            //Line 489 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD") && !AuthorizationContext.Current.CheckUserAccess("AORD") && !AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");
            //Line 489 :             if (!AuthorizationContext.Current.CheckUserAccess("IORD") && !AuthorizationContext.Current.CheckUserAccess("AORD") && !AuthorizationContext.Current.CheckUserAccess("EORD"))
            content = content.Replace("if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\"))", "if (!AuthorizationContext.Current.CheckUserAccess(\"IORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"AORD\", \"ORD\") && !AuthorizationContext.Current.CheckUserAccess(\"EORD\", \"ORD\"))");

            if (originalContent != content)
            {
                PendEdit(file);

                SaveFile(file, content);
            }
        }

        private static void CreateSvcFiles(string file)
        {
            File.AppendAllText(@"c:\teste.txt",
                "<service behaviorConfiguration=\"customBehavior\" name=\"ibba.raroc.Wcf.{0}\">" +
                    "<endpoint address=\"\" binding=\"wsHttpBinding\" bindingConfiguration=\"wsBinding\" contract=\"ibba.raroc.Wcf.Interfaces.ISCParametrosRaroc\" />" +
                    "<endpoint address=\"mex\" binding=\"mexHttpBinding\" contract=\"IMetadataExchange\" />" +
                 "</service>"
                );

            //File.AppendAllText(Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)) + ".svc", string.Format("<%@ ServiceHost Language=\"C#\" Debug=\"true\" Service=\"ibba.raroc.Wcf.{0}\" CodeBehind=\"{0}.svc.cs\" %>", Path.GetFileNameWithoutExtension(file)));
            //File.Copy(file, Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)) + ".svc.cs", true);
            //File.Delete(file);
        }

        private static void ModifyAssemblyVersion(string file)
        {
            string originalContent = File.ReadAllText(file, Encoding.Default);
            string[] readText = File.ReadAllLines(file, Encoding.Default);

            var versionInfoLines = readText.Where(t => t.Contains("[assembly: AssemblyVersion") && !t.StartsWith(@"//"));
            string versionFile = string.Empty;
            string versionPropose = string.Empty;

            foreach (string item in versionInfoLines)
            {
                versionFile = item.Substring(item.IndexOf('(') + 2, item.LastIndexOf(')') - item.IndexOf('(') - 3);

                //if (version != "1.0.0.0")
                {
                    File.AppendAllText("c:\\version.txt", file + " | " + versionFile + ";");
                    File.AppendAllText("c:\\version.txt", Environment.NewLine);
                }
            }

            if (_assemblyVersions.ContainsKey(file))
            {
                versionPropose = _assemblyVersions[file];

                if (versionPropose != versionFile)
                {
                    string content = originalContent.Replace("[assembly: AssemblyVersion(\"" + versionFile + "\")]", "[assembly: AssemblyVersion(\"" + versionPropose + "\")]");
                    content = content.Replace("[assembly: AssemblyFileVersion(\"" + versionFile + "\")]", "[assembly: AssemblyFileVersion(\"" + versionPropose + "\")]");

                    if (originalContent != content)
                    {
                        PendEdit(file);

                        SaveFile(file, content);
                    }
                }
            }
        }

        #endregion

        #region Unificacao Portas

        //private static void ModifyCustomBinding(XDocument document, ref bool fileUpdated)
        //{
        //    List<XElement> elements = (from c in document.Descendants()
        //                               where c.Name.LocalName.Equals("customBinding")
        //                               select (XElement)c).ToList();

        //    List<XElement> elements2 = (from c in document.Descendants()
        //                                where (c.Name.LocalName.Equals("endpoint") &&
        //                                      c.Attributes().Any(e => e.Name.LocalName == "contract" && e.Value.ToLower().Equals("imetadataexchange")))
        //                                select (XElement)c).ToList();

        //    if (elements.Count() > 0 && elements2.Count() > 0)
        //    {
        //        WriteText("-----MetadataExchangeTcpBinding-----");

        //        foreach (XElement element in elements)
        //        {
        //            if (element.Elements().ToList().Find(a => a.Name.LocalName == "binding" &&
        //                    a.Attributes().ToList().Find(af => af.Name.LocalName == "name" && af.Value == "MetadataExchangeTcpBinding") != null)
        //                == null)
        //            {
        //                WriteText(element.ToString());

        //                XElement tcpTransportElement = new XElement(XName.Get("tcpTransport", element.Name.NamespaceName));
        //                tcpTransportElement.Add(new XAttribute(XName.Get("portSharingEnabled", element.Name.NamespaceName), "true"));

        //                XElement bindingElement = new XElement(XName.Get("binding", element.Name.NamespaceName));
        //                bindingElement.Add(new XAttribute(XName.Get("name", element.Name.NamespaceName), "MetadataExchangeTcpBinding"));
        //                bindingElement.Add(tcpTransportElement);

        //                element.Add(bindingElement);

        //                fileUpdated = true;

        //                WriteText(element.ToString());
        //            }
        //        }
        //    }

        //    if (elements.Count() == 0 && elements2.Count() > 0)
        //    {
        //        WriteText("-----MetadataExchangeTcpBinding Add-----");

        //        XElement bindingsElement = document.Descendants().ToList().Find(c => c.Name.LocalName.Equals("bindings"));

        //        if (bindingsElement != null)
        //        {
        //            WriteText(bindingsElement.ToString());

        //            XElement tcpTransportElement = new XElement(XName.Get("tcpTransport", bindingsElement.Name.NamespaceName));
        //            tcpTransportElement.Add(new XAttribute(XName.Get("portSharingEnabled", bindingsElement.Name.NamespaceName), "true"));

        //            XElement bindingElement = new XElement(XName.Get("binding", bindingsElement.Name.NamespaceName));
        //            bindingElement.Add(new XAttribute(XName.Get("name", bindingsElement.Name.NamespaceName), "MetadataExchangeTcpBinding"));
        //            bindingElement.Add(tcpTransportElement);

        //            XElement customBindingElement = new XElement(XName.Get("customBinding", bindingsElement.Name.NamespaceName));
        //            customBindingElement.Add(bindingElement);

        //            bindingsElement.Add(customBindingElement);

        //            fileUpdated = true;

        //            WriteText(bindingsElement.ToString());
        //        }
        //    }
        //}

        private static void ModifyNetTcpBinding(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("netTcpBinding")
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----netTcpBinding-----");

                foreach (XElement elementNet in elements)
                {
                    foreach (XElement element in elementNet.Elements())
                    {
                        if (element.Name.LocalName == "binding")
                        {
                            if (element.Attributes().ToList().Find(af => af.Name.LocalName == "portSharingEnabled") == null)
                            {
                                WriteText(element.ToString());

                                element.Add(new XAttribute(XName.Get("portSharingEnabled", element.Name.NamespaceName), "true"));

                                fileUpdated = true;

                                WriteText(element.ToString());
                            }
                            else
                            {
                                if (element.Attributes().ToList().Find(af => af.Name.LocalName == "portSharingEnabled").Value.ToLower() != "true")
                                {
                                    WriteText(element.ToString());

                                    element.Attributes().ToList().Find(af => af.Name.LocalName == "portSharingEnabled").Value = "true";

                                    fileUpdated = true;

                                    WriteText(element.ToString());
                                }
                            }
                        }
                    }
                }
            }
        }

        private static void ModifyTcpTransport(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("tcpTransport")
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----TcpTransport-----");

                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(a => a.Name.LocalName == "portSharingEnabled") == null)
                    {
                        WriteText(element.ToString());

                        element.Add(new XAttribute(XName.Get("portSharingEnabled", element.Name.NamespaceName), "true"));

                        fileUpdated = true;

                        WriteText(element.ToString());
                    }
                    else
                    {
                        if (element.Attributes().ToList().Find(af => af.Name.LocalName == "portSharingEnabled").Value.ToLower() != "true")
                        {
                            WriteText(element.ToString());

                            element.Attributes().ToList().Find(af => af.Name.LocalName == "portSharingEnabled").Value = "true";

                            fileUpdated = true;

                            WriteText(element.ToString());
                        }
                    }
                }
            }
        }

        //private static void ModifyMex(XDocument document, ref bool fileUpdated)
        //{
        //    List<XElement> elements = (from c in document.Descendants()
        //                               where (c.Name.LocalName.Equals("endpoint") &&
        //                                     c.Attributes().Any(e => e.Name.LocalName == "contract" && e.Value.ToLower().Equals("imetadataexchange")))
        //                               select (XElement)c).ToList();

        //    if (elements.Count() > 0)
        //    {
        //        WriteText("-----endpoint mex-----");

        //        foreach (XElement element in elements)
        //        {
        //            if (element.Attributes().ToList().Find(a => a.Name.LocalName == "binding") != null)
        //            {
        //                if (element.Attributes().ToList().Find(a => a.Name.LocalName == "binding").Value != "customBinding")
        //                {
        //                    WriteText(element.ToString());

        //                    element.Attributes().ToList().Find(a => a.Name.LocalName == "binding").Value = "customBinding";

        //                    fileUpdated = true;

        //                    WriteText(element.ToString());
        //                }
        //            }
        //            else
        //            {
        //                WriteText(element.ToString());

        //                element.Add(new XAttribute(XName.Get("binding", element.Name.NamespaceName), "customBinding"));

        //                fileUpdated = true;

        //                WriteText(element.ToString());
        //            }

        //            if (element.Attributes().ToList().Find(a => a.Name.LocalName == "bindingConfiguration") != null)
        //            {
        //                if (element.Attributes().ToList().Find(a => a.Name.LocalName == "bindingConfiguration").Value != "MetadataExchangeTcpBinding")
        //                {
        //                    WriteText(element.ToString());

        //                    element.Attributes().ToList().Find(a => a.Name.LocalName == "bindingConfiguration").Value = "MetadataExchangeTcpBinding";

        //                    fileUpdated = true;

        //                    WriteText(element.ToString());
        //                }
        //            }
        //            else
        //            {
        //                WriteText(element.ToString());

        //                element.Add(new XAttribute(XName.Get("bindingConfiguration", element.Name.NamespaceName), "MetadataExchangeTcpBinding"));

        //                fileUpdated = true;

        //                WriteText(element.ToString());
        //            }
        //        }
        //    }
        //}

        private static void ModifySetMexTcpBinding(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("endpoint") &&
                                             c.Attributes().Any(e => e.Name.LocalName == "contract" && e.Value.ToLower().Equals("imetadataexchange")))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----endpoint mex-----");

                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(a => a.Name.LocalName == "binding") != null)
                    {
                        if (element.Attributes().ToList().Find(a => a.Name.LocalName == "binding").Value != "netTcpBinding")
                        {
                            WriteText(element.ToString());

                            element.Attributes().ToList().Find(a => a.Name.LocalName == "binding").Value = "netTcpBinding";

                            fileUpdated = true;

                            WriteText(element.ToString());
                        }
                    }
                    else
                    {
                        WriteText(element.ToString());

                        element.Add(new XAttribute(XName.Get("binding", element.Name.NamespaceName), "netTcpBinding"));

                        fileUpdated = true;

                        WriteText(element.ToString());
                    }

                    if (element.Attributes().ToList().Find(a => a.Name.LocalName == "bindingConfiguration") != null)
                    {
                        if (element.Attributes().ToList().Find(a => a.Name.LocalName == "bindingConfiguration").Value != "Basic")
                        {
                            WriteText(element.ToString());

                            element.Attributes().ToList().Find(a => a.Name.LocalName == "bindingConfiguration").Value = "Basic";

                            fileUpdated = true;

                            WriteText(element.ToString());
                        }
                    }
                    else
                    {
                        WriteText(element.ToString());

                        element.Add(new XAttribute(XName.Get("bindingConfiguration", element.Name.NamespaceName), "Basic"));

                        fileUpdated = true;

                        WriteText(element.ToString());
                    }
                }
            }
        }

        private static void NotifyMexBinding(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("endpoint") &&
                                             c.Attributes().Any(e => e.Name.LocalName == "contract" && e.Value.ToLower().Equals("imetadataexchange")))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----endpoint mex-----");

                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(a => a.Name.LocalName == "bindingConfiguration") == null)
                    {
                        fileUpdated = true;
                    }
                }
            }
        }

        private static void ModifyPortServer(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("add") &&
                                             c.Attributes().Any(e => e.Name.LocalName == "baseAddress"))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----Port Server-----");

                foreach (XElement element in elements)
                {
                    if (Uri.IsWellFormedUriString(element.Attributes().ToList().Find(a => a.Name.LocalName == "baseAddress").Value, UriKind.RelativeOrAbsolute))
                    {
                        UriBuilder uri = new UriBuilder(element.Attributes().ToList().Find(a => a.Name.LocalName == "baseAddress").Value);

                        if (uri.Port != -1 && uri.Port != 62000)
                        {
                            WriteText(element.ToString());

                            fileUpdated = true;

                            uri.Port = 62000;
                            element.Attributes().ToList().Find(a => a.Name.LocalName == "baseAddress").Value = uri.ToString();

                            WriteText(element.ToString());
                        }
                    }
                }
            }
        }

        private static void ModifyPortClient(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("endpoint") &&
                                             c.Attributes().Any(e => e.Name.LocalName == "address" && (e.Value != "mex" && !string.IsNullOrEmpty(e.Value))))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----Port Client-----");

                foreach (XElement element in elements)
                {
                    if (Uri.IsWellFormedUriString(element.Attributes().ToList().Find(a => a.Name.LocalName == "address").Value, UriKind.RelativeOrAbsolute))
                    {
                        UriBuilder uri = new UriBuilder(element.Attributes().ToList().Find(a => a.Name.LocalName == "address").Value);

                        if (uri.Port != 62000 && uri.Port != -1)
                        {
                            WriteText(element.ToString());

                            uri.Port = 62000;
                            element.Attributes().ToList().Find(a => a.Name.LocalName == "address").Value = uri.ToString();

                            fileUpdated = true;

                            WriteText(element.ToString());
                        }
                    }
                }
            }
        }

        private static void ModifyServiceReferences(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("MetadataSource") || c.Name.LocalName.Equals("MetadataFile"))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----MetadataSource - MetadataFile-----");

                foreach (XElement element in elements)
                {
                    XAttribute metadataSourceAddress = element.Attributes().ToList().Find(a => a.Name.LocalName == "Address");

                    if (metadataSourceAddress != null && Uri.IsWellFormedUriString(metadataSourceAddress.Value, UriKind.RelativeOrAbsolute))
                    {
                        UriBuilder uri = new UriBuilder(metadataSourceAddress.Value);

                        if (uri.Port != -1 && uri.Port != 62000)
                        {
                            WriteText(element.ToString());

                            uri.Port = 62000;
                            metadataSourceAddress.Value = uri.ToString();

                            fileUpdated = true;

                            WriteText(element.ToString());
                        }
                    }

                    XAttribute metadataFileSourceUrl = element.Attributes().ToList().Find(a => a.Name.LocalName == "SourceUrl");

                    if (metadataFileSourceUrl != null && Uri.IsWellFormedUriString(metadataFileSourceUrl.Value, UriKind.RelativeOrAbsolute))
                    {
                        UriBuilder uri = new UriBuilder(metadataFileSourceUrl.Value);

                        if (uri.Port != -1 && uri.Port != 62000)
                        {
                            WriteText(element.ToString());

                            uri.Port = 62000;
                            metadataFileSourceUrl.Value = uri.ToString();

                            fileUpdated = true;

                            WriteText(element.ToString());
                        }
                    }
                }
            }
        }

        #endregion

        #region Modify Config Client

        private static void RemoveClientBehaviors(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("behaviors")
                                       select (XElement)c).ToList();

            List<XElement> elementsClient = (from c in document.Descendants()
                                             where c.Name.LocalName.Equals("service") && c.Elements().ToList().Find(s => s.Name.LocalName.Equals("host")) != null
                                             select (XElement)c).ToList();

            if (elements.Count() > 0 && elementsClient.Count == 0)
            {
                WriteText("-----Remoção das configurações de behavior -----");

                foreach (XElement element in elements)
                {
                    element.Remove();
                }

                fileUpdated = true;
            }
        }

        private static void RemoveClientBindings(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("bindings")
                                       select (XElement)c).ToList();

            List<XElement> elementsClient = (from c in document.Descendants()
                                             where c.Name.LocalName.Equals("service") && c.Elements().ToList().Find(s => s.Name.LocalName.Equals("host")) != null
                                             select (XElement)c).ToList();

            if (elements.Count() > 0 && elementsClient.Count == 0)
            {
                WriteText("-----Remoção das configurações de Binding-----");

                foreach (XElement element in elements)
                {
                    element.Remove();
                }

                fileUpdated = true;
            }
        }

        private static void ModifyClientEndpoint(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("endpoint"))
                                       select (XElement)c).ToList();

            List<XElement> elementsClient = (from c in document.Descendants()
                                             where c.Name.LocalName.Equals("client")
                                             select (XElement)c).ToList();

            if (elements.Count() > 0 && elementsClient.Count > 0)
            {
                WriteText("-----Alteração do binding Configuration do endpoint-----");

                foreach (XElement element in elements)
                {

                    XAttribute bindingAttribute = element.Attribute("binding");
                    bool changeBinding = false;

                    if (bindingAttribute == null)
                    {
                        bindingAttribute = new XAttribute("binding", "netTcpBinding");
                        element.Add(bindingAttribute);
                        changeBinding = true;

                        fileUpdated = true;
                    }
                    else if (bindingAttribute.Value != "mexTcpBinding" && bindingAttribute.Value != "netTcpBinding")
                    {
                        changeBinding = true;
                        bindingAttribute.SetValue("netTcpBinding");

                        fileUpdated = true;
                    }

                    if (changeBinding)
                    {
                        XAttribute bindingConfigurationAttribute = element.Attribute("bindingConfiguration");
                        if (bindingConfigurationAttribute != null)
                        {
                            bindingConfigurationAttribute.Remove();
                            fileUpdated = true;
                        }

                        XAttribute behaviorConfigurationAttribute = element.Attribute("behaviorConfiguration");
                        if (behaviorConfigurationAttribute != null)
                        {
                            behaviorConfigurationAttribute.Remove();
                            fileUpdated = true;
                        }
                    }
                }
            }
        }

        #endregion

        #region Modify Config Service

        private static void IncludeSystemDiagnosticsTag(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("configuration")
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                string documentText = document.ToString();

                WriteText("-----IncludeSystemDiagnosticsTag-----");

                StringBuilder strElement = new StringBuilder();
                strElement.Append("<root>");
                strElement.Append("<system.diagnostics>");
                strElement.Append("<sources>");
                strElement.Append("<source name=\"System.ServiceModel\" switchValue=\"Error\" propagateActivity=\"true\">");
                strElement.Append("<listeners>");
                strElement.Append("<add name=\"ErrorLogger\" />");
                strElement.Append("</listeners>");
                strElement.Append("</source>");
                strElement.Append("</sources>");
                strElement.Append("<sharedListeners>");
                //strElement.Append("<add name=\"ErrorLogger\" type=\"PSE.Framework.ErrorLogging.ErrorLoggerTraceListener, PSE.Framework.ErrorLogging, Version=4.0.0.0, Culture=Neutral, PublicKeyToken=d12c15b5d58bc696\" />");
                strElement.Append("<add name=\"ErrorLogger\" type=\"System.Diagnostics.EventLogTraceListener\" initializeData=\"TraceListenerLog\" />");
                //strElement.Append("<add name=\"ErrorLogger\" type=\"System.Diagnostics.XmlWriterTraceListener\" initializeData=\"C:\\LOGS\\Traces.svclog\"  />");
                strElement.Append("</sharedListeners>");
                strElement.Append("<trace autoflush=\"true\" />");
                strElement.Append("</system.diagnostics>");
                strElement.Append("</root>");

                XElement xElement = XElement.Parse(strElement.ToString());
                //remover os behaviors existentes
                foreach (XElement element in elements)
                {
                    XElement diagnosticsElement = element.Elements().ToList().Find(e => e.Name.LocalName == "system.diagnostics");

                    if (diagnosticsElement != null)
                    {
                        diagnosticsElement.Remove();
                    }

                    //foreach (XElement item in xElement.Elements())
                    //{
                    //    element.Add(item);
                    //}
                }

                string documentText2 = document.ToString();

                fileUpdated = documentText2 != documentText;
            }
        }

        private static void ModifyServiceBehavior(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("serviceBehaviors")
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                string documentText = document.ToString();

                WriteText("-----Alteração das configurações de behavior -----");

                StringBuilder strElement = new StringBuilder();
                strElement.Append("<root>");
                strElement.Append("<!-- Construção do Behavior do Serviço -->");
                strElement.Append("<behavior name=\"Basic\">");
                strElement.Append("<!-- Contexto de Autorização do Sinacor-->");
                strElement.Append("<serviceAuthorization serviceAuthorizationManagerType=\"Sinacor.Infra.Service.Security.Authorization.SinacorAuthorizationManager,Sinacor.Infra.Service.Security.Authorization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9b0dac35dd685e79\" />");
                strElement.Append("<!-- Credenciais do Serviço -->");
                strElement.Append("<!-- Permite a publicação do MEX -->");
                strElement.Append("<serviceMetadata />");
                strElement.Append("<!-- Aumenta o número máximo de concorrências, para evitar quedas de serviços -->");
                strElement.Append("<serviceThrottling maxConcurrentCalls=\"100\" maxConcurrentInstances=\"100\" maxConcurrentSessions=\"100\" />");
                strElement.Append("<!-- Aumenta a quantidade de items ( DataContracts) que podem ser serializados-->");
                strElement.Append("<dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />");
                strElement.Append("</behavior>");
                strElement.Append("<!-- Construção do Behavior do Serviço -->");
                strElement.Append("<behavior name=\"Transport\">");
                strElement.Append("<!-- Contexto de Autorização do Sinacor-->");
                strElement.Append("<serviceAuthorization serviceAuthorizationManagerType=\"Sinacor.Infra.Service.Security.Authorization.SinacorAuthorizationManager,Sinacor.Infra.Service.Security.Authorization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9b0dac35dd685e79\" />");
                strElement.Append("<!-- Credenciais do Serviço -->");
                strElement.Append("<!-- Permite a publicação do MEX -->");
                strElement.Append("<serviceMetadata />");
                strElement.Append("<!-- Aumenta o número máximo de concorrências, para evitar quedas de serviços -->");
                strElement.Append("<serviceThrottling maxConcurrentCalls=\"100\" maxConcurrentInstances=\"100\" maxConcurrentSessions=\"100\" />");
                strElement.Append("<!-- Aumenta a quantidade de items ( DataContracts) que podem ser serializados-->");
                strElement.Append("<dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />");
                strElement.Append("</behavior>");
                strElement.Append("<!-- Construção do Behavior do Serviço -->");
                strElement.Append("<behavior name=\"Federated\">");
                strElement.Append("<!-- Contexto de Autorização do Sinacor-->");
                strElement.Append("<serviceAuthorization serviceAuthorizationManagerType=\"Sinacor.Infra.Service.Security.Authorization.SinacorAuthorizationManager,Sinacor.Infra.Service.Security.Authorization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9b0dac35dd685e79\" />");
                strElement.Append("<!-- Credenciais do Serviço -->");
                strElement.Append("<serviceCredentials>");
                strElement.Append("<!-- Autenticação por IssuedToken -->");
                strElement.Append("<issuedTokenAuthentication allowUntrustedRsaIssuers=\"true\" revocationMode=\"NoCheck\" certificateValidationMode=\"None\">");
                strElement.Append("<knownCertificates>");
                strElement.Append("<add storeLocation=\"LocalMachine\" storeName=\"TrustedPeople\" findValue=\"CN=SinacorSTSAuthority\" x509FindType=\"FindBySubjectDistinguishedName\" />");
                strElement.Append("<add storeLocation=\"LocalMachine\" storeName=\"TrustedPeople\" findValue=\"CN=SinacorService\" x509FindType=\"FindBySubjectDistinguishedName\" />");
                strElement.Append("</knownCertificates>");
                strElement.Append("</issuedTokenAuthentication>");
                strElement.Append("</serviceCredentials>");
                strElement.Append("<!-- Permite a publicação do MEX -->");
                strElement.Append("<serviceMetadata />");
                strElement.Append("<!-- Aumenta o número máximo de concorrências, para evitar quedas de serviços -->");
                strElement.Append("<serviceThrottling maxConcurrentCalls=\"100\" maxConcurrentInstances=\"100\" maxConcurrentSessions=\"100\" />");
                strElement.Append("<!-- Aumenta a quantidade de items ( DataContracts) que podem ser serializados-->");
                strElement.Append("<dataContractSerializer maxItemsInObjectGraph=\"2147483647\" />");
                strElement.Append("</behavior>");
                strElement.Append("</root>");

                XElement xElement = XElement.Parse(strElement.ToString());
                //remover os behaviors existentes
                foreach (XElement element in elements)
                {
                    element.RemoveNodes();

                    foreach (XElement item in xElement.Elements("behavior"))
                    {
                        element.Add(item);
                    }
                }

                string documentText2 = document.ToString();

                fileUpdated = documentText2 != documentText;
            }
        }

        private static void ModifyServiceBinding(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("bindings")
                                       select (XElement)c).ToList();


            if (elements.Count() > 0)
            {
                string documentText = document.ToString();

                WriteText("-----Alteração das configurações de binding -----");

                StringBuilder strElement = new StringBuilder();
                strElement.Append("<root>");
                strElement.Append("<netTcpBinding>");
                strElement.Append("<binding name=\"Basic\" maxBufferPoolSize=\"3145728\" maxReceivedMessageSize=\"2147483647\" maxBufferSize=\"2147483647\" closeTimeout=\"00:10:00\" openTimeout=\"00:10:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:10:00\">");
                strElement.Append("<security mode=\"None\">");
                strElement.Append("</security>");
                strElement.Append("</binding>");
                strElement.Append("<binding name=\"Transport\" maxBufferPoolSize=\"3145728\" maxReceivedMessageSize=\"2147483647\" maxBufferSize=\"2147483647\" closeTimeout=\"00:10:00\" openTimeout=\"00:10:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:10:00\">");
                strElement.Append("<security mode=\"Transport\">");
                strElement.Append("<transport protectionLevel=\"EncryptAndSign\" />");
                strElement.Append("</security>");
                strElement.Append("</binding>");
                strElement.Append("</netTcpBinding>");
                strElement.Append("<customBinding>");
                strElement.Append("<!-- Binding ServiceTCPBinding-->");
                strElement.Append("<binding name=\"Federated\">");
                strElement.Append("<security authenticationMode=\"SecureConversation\" requireSecurityContextCancellation=\"true\">");
                strElement.Append("<secureConversationBootstrap authenticationMode=\"IssuedToken\">");
                strElement.Append("<!-- Definição do Típo do Token SAML -->");
                strElement.Append("<issuedTokenParameters tokenType=\"http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1\" />");
                strElement.Append("</secureConversationBootstrap>");
                strElement.Append("</security>");
                strElement.Append("<binaryMessageEncoding />");
                strElement.Append("<!-- Definição do Protocolo Tcp-->");
                strElement.Append("<tcpTransport />");
                strElement.Append("</binding>");
                strElement.Append("</customBinding>");
                strElement.Append("</root>");

                XElement xElement = XElement.Parse(strElement.ToString());
                //remover os behaviors existentes
                foreach (XElement element in elements)
                {
                    element.RemoveNodes();

                    foreach (XElement item in xElement.Elements())
                    {
                        element.Add(item);
                    }
                }

                string documentText2 = document.ToString();

                fileUpdated = documentText2 != documentText;
            }
        }

        private static void ModifyService(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("service"))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----Alteração das configurações de binding -----");

                foreach (XElement element in elements)
                {
                    XAttribute behaviorAttribute = element.Attribute("behaviorConfiguration");
                    if (behaviorAttribute == null)//se n existe
                    {
                        behaviorAttribute = new XAttribute("behaviorConfiguration", "Basic");
                        element.Add(behaviorAttribute);
                        fileUpdated = true;
                    }
                    else if (behaviorAttribute.Value != "Basic")//se existe e ainda n foi alterado
                    {
                        behaviorAttribute.SetValue("Basic");
                        fileUpdated = true;
                    }

                    //recuperar os endpoints associados

                    List<XElement> endpoints = element.Elements("endpoint").ToList();
                    if (endpoints != null)
                    {
                        foreach (XElement endpoint in endpoints)
                        {
                            XAttribute bindingAttribute = endpoint.Attribute("binding");

                            if (bindingAttribute == null)//se n existe adiciona
                            {
                                bindingAttribute = new XAttribute("binding", "netTcpBinding");
                                endpoint.Add(bindingAttribute);
                                fileUpdated = true;
                            }
                            else if (bindingAttribute.Value != "mexTcpBinding" && bindingAttribute.Value != "netTcpBinding")//se existe e nao e mex, alterar
                            {
                                bindingAttribute.SetValue("netTcpBinding");
                                fileUpdated = true;
                            }

                            if (bindingAttribute.Value != "mexTcpBinding")
                            {
                                XAttribute bindingConfigurationAttribute = endpoint.Attribute("bindingConfiguration");
                                if (bindingConfigurationAttribute == null)
                                {
                                    bindingConfigurationAttribute = new XAttribute("bindingConfiguration", "Basic");
                                    endpoint.Add(bindingConfigurationAttribute);
                                    fileUpdated = true;
                                }
                                else if (bindingConfigurationAttribute.Value != "Basic")
                                {
                                    bindingConfigurationAttribute.SetValue("Basic");
                                    fileUpdated = true;
                                }
                            }
                        }
                    }
                }
            }
        }

        #endregion

        #region EnterpriseLibrary

        private static void ModifyVersionEnterpriseLibraryCaching(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("section") && (c.Attributes().ToList().Find(e => e.Value == "cachingConfiguration") != null))
                                       select (XElement)c).ToList();

            string newVersion = "5.0.414.0";

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyVersionEnterpriseLibraryCaching-----");

                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value != "Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=" + newVersion + ", Culture=neutral, PublicKeyToken=31bf3856ad364e35")
                    {
                        WriteText(element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value);

                        element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value = "Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=" + newVersion + ", Culture=neutral, PublicKeyToken=31bf3856ad364e35";

                        fileUpdated = true;

                        WriteText(element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value);
                    }
                }
            }
        }

        private static void ModifyVersionEnterpriseLibraryCachingConfiguration(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("add") &&
                                       (c.Attributes().ToList().Find(e => e.Name.LocalName == "backingStoreName" && e.Value == "Null Storage") != null))
                                       select (XElement)c).ToList();

            elements.AddRange((from c in document.Descendants()
                               where (c.Name.LocalName.Equals("add") &&
                               (c.Attributes().ToList().Find(e => e.Name.LocalName == "name" && e.Value == "Null Storage") != null))
                               select (XElement)c).ToList());

            string oldVersion = "3.1.0.0";
            string newVersion = "5.0.414.0";

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyVersionEnterpriseLibraryCachingConfiguration-----");

                foreach (XElement element in elements)
                {
                    WriteText(element.ToString());

                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "encryptionProviderName") != null &&
                        element.Attributes().ToList().Find(e => e.Name.LocalName == "type") != null &&
                        element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value == "Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=" + oldVersion + ", Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
                    {
                        element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value = "Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=" + newVersion + ", Culture=neutral, PublicKeyToken=31bf3856ad364e35";
                        fileUpdated = true;
                    }

                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "name" && e.Value == "Cache Manager") != null &&
                        element.Attributes().ToList().Find(e => e.Name.LocalName == "type") == null)
                    {
                        element.Add(new XAttribute(XName.Get("type", element.Name.NamespaceName), "Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=" + newVersion + ", Culture=neutral, PublicKeyToken=31bf3856ad364e35"));
                        fileUpdated = true;
                    }

                    if (element.Attributes().ToList().Find(e => e.Value == "Null Storage").Value != "NullBackingStore")
                    {
                        element.Attributes().ToList().Find(e => e.Value == "Null Storage").Value = "NullBackingStore";

                        fileUpdated = true;
                    }

                    WriteText(element.ToString());
                }
            }
        }

        private static void ModifyVersionEnterpriseDataConfiguration(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("section") && (c.Attributes().ToList().Find(e => e.Value == "dataConfiguration") != null))
                                       select (XElement)c).ToList();

            string oldVersion = "3.1.0.0";

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyVersionEnterpriseDataConfiguration-----");

                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value == "Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=" + oldVersion + ", Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
                    {
                        element.Remove();
                        fileUpdated = true;
                    }
                }
            }
        }

        private static void ModifyVersionEnterpriseLibraryLogging(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("section") && (c.Attributes().ToList().Find(e => e.Value == "loggingConfiguration") != null))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyVersionEnterpriseLibraryLogging-----");

                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value == "Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
                    {
                        element.Remove();
                        fileUpdated = true;
                    }

                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "type").Value == "Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
                    {
                        element.Remove();
                        fileUpdated = true;
                    }
                }
            }
        }

        private static void ModifyVersionEnterpriseLibraryLoggingConfiguration(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("loggingConfiguration") && (c.Attributes().ToList().Find(e => e.Value == "Logging Application Block") != null))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyVersionEnterpriseLibraryLoggingConfiguration-----");

                foreach (XElement element in elements)
                {
                    element.Remove();
                    fileUpdated = true;
                }
            }
        }

        private static void ModifyReferenceEnterpriseLibrary(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Reference") &&
                                       (c.Attributes().ToList().Find(e => e.Name.LocalName == "Include" && e.Value.StartsWith("Microsoft.Practices")) != null))
                                       select (XElement)c).ToList();

            string oldVersion = "3.1.0.0";
            string newVersion = "5.0.414.0";
            string oldToken = "b03f5f7f11d50a3a";
            string newToken = "31bf3856ad364e35";

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyReferenceEnterpriseLibrary-----");

                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "Include").Value.Contains("Microsoft.Practices.ObjectBuilder"))
                    {
                        element.Remove();
                        fileUpdated = true;
                    }

                    WriteText(element.Attributes().ToList().Find(e => e.Name.LocalName == "Include").Value);

                    string reference = element.Attributes().ToList().Find(e => e.Name.LocalName == "Include").Value;

                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "Include").Value != reference.Replace("Version=" + oldVersion, "Version=" + newVersion).Replace("PublicKeyToken=" + oldToken, "PublicKeyToken=" + newToken))
                    {
                        element.Attributes().ToList().Find(e => e.Name.LocalName == "Include").Value = reference.Replace("Version=" + oldVersion, "Version=" + newVersion).Replace("PublicKeyToken=" + oldToken, "PublicKeyToken=" + newToken);
                        fileUpdated = true;
                    }

                    WriteText(element.Attributes().ToList().Find(e => e.Name.LocalName == "Include").Value);
                }
            }
        }

        #endregion

        #region Reference Framework

        private static void ModifyReferencePrivate(string file, XDocument document, ref bool fileUpdated, bool value)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Reference"))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyReferencePrivate-----");

                foreach (XElement element in elements)
                {
                    XAttribute include = element.Attributes().ToList().Find(e => e.Name.LocalName == "Include");
                    XElement hintPath = element.Elements().ToList().Find(e => e.Name.LocalName == "HintPath");

                    if (include != null && hintPath != null)
                    {
                        //if (include.Value.Contains("ibba.raroc"))
                        {
                            XElement privateElement = element.Elements().ToList().Find(e => e.Name.LocalName == "Private");

                            if (privateElement == null)
                            {
                                element.SetElementValue(XName.Get("Private", element.Name.NamespaceName), Convert.ToString(value));
                                fileUpdated = true;

                                WriteText(string.Format("Private - {0}", Convert.ToString(value)));

                            }
                            else
                            {
                                if (Convert.ToBoolean(privateElement.Value) != value)
                                {
                                    string oldValue = privateElement.Value;

                                    privateElement.Value = Convert.ToString(value);

                                    fileUpdated = true;

                                    WriteText(string.Format("Private - {0} - {1}", oldValue, Convert.ToString(value)));
                                }
                            }
                        }
                    }
                }
            }
        }

        private static void ModifyProjectReferencePrivate(string file, XDocument document, ref bool fileUpdated, bool value)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("ProjectReference"))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyProjectReferencePrivate-----");

                foreach (XElement element in elements)
                {
                    XAttribute include = element.Attributes().ToList().Find(e => e.Name.LocalName == "Include");

                    if (include != null)
                    {
                        //if (include.Value.Contains("ibba.raroc"))
                        {
                            XElement privateElement = element.Elements().ToList().Find(e => e.Name.LocalName == "Private");

                            if (privateElement == null)
                            {
                                element.SetElementValue(XName.Get("Private", element.Name.NamespaceName), Convert.ToString(value));
                                fileUpdated = true;

                                WriteText(string.Format("Private - {0}", Convert.ToString(value)));

                            }
                            else
                            {
                                if (Convert.ToBoolean(privateElement.Value) != value)
                                {
                                    string oldValue = privateElement.Value;

                                    privateElement.Value = Convert.ToString(value);

                                    fileUpdated = true;

                                    WriteText(string.Format("Private - {0} - {1}", oldValue, Convert.ToString(value)));
                                }
                            }
                        }
                    }
                }
            }
        }

        private static void ModifyReferenceSpecificVersion(string file, XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Reference") &&
                                       (c.Attributes().ToList().Find(e => e.Name.LocalName == "Include" && e.Value.StartsWith("PSE.Framework")) != null))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                WriteText("-----ModifyReferenceSpecificVersion-----");

                foreach (XElement element in elements)
                {
                    XElement privateElement = element.Elements().ToList().Find(e => e.Name.LocalName == "SpecificVersion");

                    if (privateElement == null || privateElement.Value != "True")
                    {
                        element.SetElementValue(XName.Get("SpecificVersion", element.Name.NamespaceName), Convert.ToString(true));
                        fileUpdated = true;
                    }

                    XAttribute includeElement = element.Attributes().ToList().Find(e => e.Name.LocalName == "Include");

                    if (privateElement != null && (!includeElement.Value.Contains("PublicKeyToken=d12c15b5d58bc696") || !includeElement.Value.Contains("Version=4.0.0.0")))
                    {
                        string oldVersion = includeElement.Value.Replace("Version=1.0.0.0", "Version=4.0.0.0");

                        if (includeElement.Value != oldVersion)
                        {
                            includeElement.Value = oldVersion;
                            fileUpdated = true;
                        }

                        if (includeElement.Value == "PSE.Framework.Messaging, Version=4.0.0.0, Culture=neutral, processorArchitecture=x86")
                        {
                            includeElement.Value = "PSE.Framework.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=d12c15b5d58bc696, processorArchitecture=x86";
                            fileUpdated = true;
                        }
                    }
                }
            }
        }

        private static void IncludePSEReference(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Reference") &&
                                       (c.Attributes().ToList().Find(e => e.Name.LocalName == "Include" && e.Value.StartsWith("PSE.Framework.Process")) != null))
                                       select (XElement)c).ToList();

            XElement assemblyName = document.Descendants().ToList().Find(e => e.Name.LocalName == "AssemblyName" && e.Value.StartsWith("Sinacor.Process") && e.Value.EndsWith("Server"));

            XElement itemGroup = document.Descendants().ToList().Find(e => e.Name.LocalName == "ItemGroup" && e.Elements().ToList().Find(e2 => e2.Name.LocalName == "Reference") != null);

            if (elements.Count() == 0 && assemblyName != null && itemGroup != null)
            {
                XElement referenceElement = new XElement(XName.Get("Reference", itemGroup.Name.NamespaceName));
                referenceElement.SetAttributeValue(XName.Get("Include"), "PSE.Framework.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=d12c15b5d58bc696, processorArchitecture=x86");
                referenceElement.Add(new XElement(XName.Get("HintPath", itemGroup.Name.NamespaceName), @"..\..\..\..\..\..\..\..\..\..\Compilados\PSE\Framework\v4\Process\PSE.Framework.Process.dll"));
                referenceElement.Add(new XElement(XName.Get("Private", itemGroup.Name.NamespaceName), "False"));
                referenceElement.Add(new XElement(XName.Get("SpecificVersion", itemGroup.Name.NamespaceName), "True"));

                itemGroup.Add(referenceElement);

                fileUpdated = true;
            }
        }

        private static void RemoveScc(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("SccProjectName") ||
                                            c.Name.LocalName.Equals("SccLocalPath") ||
                                            c.Name.LocalName.Equals("SccAuxPath") ||
                                            c.Name.LocalName.Equals("SccProvider")
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    WriteText("-----RemoveScc-----");

                    element.Remove();

                    fileUpdated = true;
                }
            }
        }

        private static void RemoveReferenceCalculationCore(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Reference") &&
                                       (c.Attributes().ToList().Find(e => e.Name.LocalName == "Include" && e.Value.Contains("Ibba.CalculationCore")) != null))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "Include").Value.Contains("Ibba.CalculationCore"))
                    {
                        WriteText("-----RemoveReferenceCalculationCore-----");
                        WriteText(element.ToString());

                        element.Remove();

                        fileUpdated = true;
                    }
                }
            }
        }

        private static void ListIncludes(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Reference") &&
                                       (c.Attributes().ToList().Find(e => e.Name.LocalName == "Include") != null))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    XElement hintPathElement = element.Elements().ToList().Find(e => e.Name.LocalName == "HintPath");
                    if (hintPathElement != null)
                    {
                        WriteText(hintPathElement.Value);
                        fileUpdated = true;
                    }
                }
            }
        }

        private static void RemoveAppSettingsMTA(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("add") && (c.Attributes().ToList().Find(e => e.Name.LocalName == "key" && e.Value == "PastaPadrao") != null))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    element.Remove();

                    fileUpdated = true;
                }
            }
        }

        private static void ChangePlatformTarget(XDocument document, ref bool fileUpdated)
        {
            var qProp = from c in document.Descendants()
                        where c.Name.LocalName.Equals("PropertyGroup") &&
                              c.Elements().ToList().Find(e => e.Name.LocalName == "OutputPath") != null
                        select (XElement)c;

            foreach (XElement group in qProp)
            {
                WriteText("-----ChangePlatformTarget-----");

                XElement platform = group.Elements().ToList().Find(e => e.Name.LocalName == "PlatformTarget");

                if (platform != null && platform.Value != "x86")
                {
                    platform.Value = "x86";
                    fileUpdated = true;
                }
                else
                {
                    if (group.Elements().ToList().Find(e => e.Name.LocalName == "ProjectGuid") == null &&
                        group.Elements().ToList().Find(e => e.Name.LocalName == "PlatformTarget") == null)
                    {
                        XNamespace ns = group.Name.Namespace;
                        platform = new XElement(ns + "PlatformTarget", "x86");
                        group.Add(platform);
                        fileUpdated = true;
                    }

                    var elements = group.Elements().ToList().Where(e => e.Name.LocalName == "PlatformTarget").ToList();

                    if (elements.Count > 1)
                    {
                        foreach (var element in elements)
                        {
                            element.Remove();
                        }

                        XNamespace ns = group.Name.Namespace;
                        platform = new XElement(ns + "PlatformTarget", "x86");
                        group.Add(platform);
                        fileUpdated = true;
                    }
                }
            }
        }

        private static void ChangePlatformTargetReference(XDocument document, ref bool fileUpdated)
        {
            int stringPos = 0;
            string newAttValue = string.Empty;

            var qRef = from c in document.Descendants()
                       where c.Name.LocalName.Equals("Reference")
                       select (XElement)c;

            foreach (XElement reference in qRef)
            {
                WriteText("-----ChangePlatformTargetReference-----");

                XAttribute refAttribute = reference.Attributes().ToList().Find(e => e.Name.LocalName == "Include" && (e.Value.ToUpper().Contains("SINACOR") || e.Value.ToUpper().Contains("PSE") || e.Value.ToUpper().Contains("IMERCADO")));

                if (refAttribute != null)
                {
                    stringPos = refAttribute.Value.IndexOf("processorArchitecture");

                    if (refAttribute.Value.Contains("processorArchitecture"))
                        newAttValue = string.Concat(refAttribute.Value.Substring(0, stringPos), "processorArchitecture=", "x86");
                    else
                        newAttValue = string.Concat(refAttribute.Value, ", processorArchitecture=", "x86");

                    if (refAttribute.Value != newAttValue)
                    {
                        refAttribute.Value = newAttValue;
                        fileUpdated = true;
                    }
                }
            }
        }

        private static void RemoveObsoletsTags(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where c.Name.LocalName.Equals("add") && c.Attributes().ToList().Find(a => a.Name.LocalName == "key" &&
                                           (a.Value == "Sinacor.Infra.Service.Security.Services.OperationLoggingEnabled" ||
                                           a.Value == "Providers" ||
                                           a.Value == "EndpointConfigPath" ||
                                           a.Value == "ClientSettingsProvider.ServiceUri" ||
                                           a.Value == "Issuer")) != null
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    element.Remove();
                }

                fileUpdated = true;
            }
        }

        private static void ModifyValues(string file, XDocument document, ref bool fileUpdated)
        {
            var elements = from c in document.Descendants()
                           select (XElement)c;

            string oldValue = string.Empty;

            foreach (XElement element in elements)
            {
                foreach (var item in _deparaServidores)
                {
                    if (element.Value.ToLower().Contains(item.Key.ToLower()))
                    {
                        oldValue = element.Value;

                        element.Value = element.Value.Replace(item.Key.ToLower(), item.Value.ToLower());

                        if (element.Value != oldValue)
                        {
                            //WriteText(element.GetAbsoluteXPath());

                            WriteText("Antes: " + oldValue);

                            WriteText("Depois: " + element.Value);

                            fileUpdated = true;
                        }
                    }

                    foreach (XAttribute attribute in element.Attributes())
                    {
                        if (attribute.Value.ToLower().Contains(item.Key.ToLower()))
                        {
                            oldValue = attribute.Value;

                            attribute.Value = attribute.Value.Replace(item.Key.ToLower(), item.Value.ToLower());

                            if (attribute.Value != oldValue)
                            {
                                //WriteText(attribute.GetAbsoluteXPath());

                                WriteText("Antes: " + oldValue);

                                WriteText("Depois: " + attribute.Value);

                                fileUpdated = true;
                            }
                        }
                    }
                }
            }
        }

        private static void ChangeOutputPath(XDocument document, ref bool fileUpdated)
        {
            var elements = from c in document.Descendants()
                           where c.Name.LocalName.Equals("OutputPath")
                           select (XElement)c;

            foreach (XElement element in elements)
            {
                string oldValue = element.Value;

                element.Value = @"..\..\Binaries\";

                if (element.Value != oldValue)
                {
                    WriteText("-----ChangeOutputPath-----");

                    WriteText(oldValue);

                    WriteText(element.Value);

                    fileUpdated = true;
                }
            }
        }

        private static void ModifyHintPathPSEComponents(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Reference"))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    XElement hintPathElement = element.Elements().ToList().Find(e => e.Name.LocalName == "HintPath");

                    if (hintPathElement != null)
                    {
                        string oldValue = hintPathElement.Value;

                        hintPathElement.Value = hintPathElement.Value.Replace(@"\Compilados\PSE\AuditLogging\", @"\Compilados\PSEComponents\AuditLogging\");
                        hintPathElement.Value = hintPathElement.Value.Replace(@"\Compilados\PSE\Communication\", @"\Compilados\PSEComponents\Communication\");
                        hintPathElement.Value = hintPathElement.Value.Replace(@"\Compilados\PSE\Hosting\", @"\Compilados\PSEComponents\Hosting\");
                        hintPathElement.Value = hintPathElement.Value.Replace(@"\Compilados\PSE\LogPackager\", @"\Compilados\PSEComponents\LogPackager\");
                        hintPathElement.Value = hintPathElement.Value.Replace(@"\Compilados\PSE\ProcessManager\", @"\Compilados\PSEComponents\ProcessManager\");
                        hintPathElement.Value = hintPathElement.Value.Replace(@"\Compilados\PSE\Updater\", @"\Compilados\PSEComponents\Updater\");
                        hintPathElement.Value = hintPathElement.Value.Replace(@"\\", @"\");

                        if (hintPathElement.Value != oldValue)
                        {
                            WriteText("-----ModifyHintPathPSEComponents-----");

                            WriteText(oldValue);

                            WriteText(hintPathElement.Value);

                            fileUpdated = true;
                        }
                    }
                }
            }
        }

        private static void ModifyVS2010Project(XDocument document, ref bool fileUpdated)
        {
            List<XElement> elements = (from c in document.Descendants()
                                       where (c.Name.LocalName.Equals("Project") &&
                                       (c.Attributes().ToList().Find(e => e.Name.LocalName == "ToolsVersion" && e.Value.Equals("3.5")) != null))
                                       select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    if (element.Attributes().ToList().Find(e => e.Name.LocalName == "ToolsVersion").Value.Equals("3.5"))
                    {
                        element.Attributes().ToList().Find(e => e.Name.LocalName == "ToolsVersion").Value = "4.0";

                        fileUpdated = true;
                    }
                }
            }

            elements = (from c in document.Descendants()
                        where c.Name.LocalName.Equals("ProductVersion")
                        select (XElement)c).ToList();

            if (elements.Count() > 0)
            {
                foreach (XElement element in elements)
                {
                    if (element.Value != "10.0.20506")
                    {
                        element.Value = "10.0.20506";

                        fileUpdated = true;
                    }
                }
            }
        }

        #endregion

        #region Save File

        private static void PendEdit(string file)
        {
            File.SetAttributes(file, FileAttributes.Normal);
        }

        private static string GetContentEncoding(string file)
        {
            string contentEncode = System.IO.File.ReadAllText(file);

            Encoding fileEncoding = GetEncoding(file);
            Encoding encoding = GetEncodingDefault();

            if (fileEncoding != encoding)
            {
                string content = System.IO.File.ReadAllText(file);

                byte[] fileEncodingBytes = fileEncoding.GetBytes(content);
                byte[] encodingBytes = Encoding.Convert(fileEncoding, encoding, fileEncodingBytes);

                char[] asciiChars = new char[encoding.GetCharCount(encodingBytes, 0, encodingBytes.Length)];
                encoding.GetChars(encodingBytes, 0, encodingBytes.Length, asciiChars, 0);

                contentEncode = new string(asciiChars);
            }

            return contentEncode;
        }

        private static Encoding GetEncoding(string file)
        {
            Encoding fileEncoding = null;

            using (var fileOpen = new StreamReader(file))
            {
                fileEncoding = fileOpen.CurrentEncoding;
            }

            return fileEncoding;
        }

        private static Encoding GetEncodingDefault()
        {
            Encoding encoding = Encoding.GetEncoding("utf-8");

            return encoding;
        }

        private static void SaveFile(string path, string content)
        {
            Encoding encoding = GetEncodingDefault();

            System.IO.File.WriteAllText(path, content, encoding);

            Encoding newFileEncoding = GetEncoding(path);
        }

        private static void WriteText(string message)
        {
            if (!_messages.ContainsKey(_fileName))
            {
                _messages.Add(_fileName, new Tuple { Key = 1, Value = new StringBuilder() });
            }
            else
            {
                _messages[_fileName].Key += 1;
            }

            _messages[_fileName].Value.Append(Environment.NewLine);
            _messages[_fileName].Value.Append(message);
            _messages[_fileName].Value.Append(Environment.NewLine);
        }

        #endregion

        private static void LoadVersions()
        {
            if (ConfigurationManager.AppSettings["AssemblyVersions"] != null)
            {
                string versions = ConfigurationManager.AppSettings["AssemblyVersions"].Trim();
                string[] versionsSplit = versions.Split(';');

                foreach (string file in versionsSplit)
                {
                    if (!string.IsNullOrEmpty(file))
                    {
                        string[] fileSplit = file.Split('|');
                        _assemblyVersions.Add(fileSplit[0].Trim(), fileSplit[1].Trim());
                    }
                }
            }
        }

        private static void DeparaServidores()
        {
            if (ConfigurationManager.AppSettings["DeparaServidores"] != null)
            {
                string servidores = ConfigurationManager.AppSettings["DeparaServidores"].Trim();
                string[] servidoresSplit = servidores.Split(';');

                foreach (string servidor in servidoresSplit)
                {
                    if (!string.IsNullOrEmpty(servidor))
                    {
                        string[] servidorSplit = servidor.Split('|');
                        _deparaServidores.Add(servidorSplit[0].Trim(), servidorSplit[1].Trim());
                    }
                }
            }
        }
    }
}